<?php
/**
 * 购买课程
 * @author 鸣枫
 *
 */
class Purchasecourse extends CT_Controller{
    
    private $member_id;     //用户ID
    
    function __construct() {
        parent::__construct();
        
        $this->member_id = $this->_uid;
        //$this->member_id = 1;
//         if(!$this->member_id && !$this->input->is_ajax_request()){
//             redirect('/login');
//         }
    }
    /**
     * 第一步验证信息
     */
    public function index(){
        try {
            $order_id = intval($_REQUEST['order_id']);    //订单ID
            if(empty($order_id))throw new Exception('订单ID为空');
            
            //$this->IsOrder($order_id);     //  验证是否购过次课包
            $course_package_info = $this->IsHours($order_id);  //验证课包课时，并返回课包信息数据
            
            $from_add = $this->input->post('from_add');
            if(!empty($from_add)){
                
                $address = $this->input->post('address');   //地址
                $linkman = $this->input->post('linkman');   //联系人
                $link_mobile = $this->input->post('link_mobile');   //电话
                $baby_name = $this->input->post('baby_name');   //名称
                $baby_sex = $this->input->post('baby_sex');   //性别
                $baby_birthday = $this->input->post('baby_birthday');   //生日
                
                //生成数组入SESSION
                $book_member = array(
                    'address'   =>  $address,
                    'linkman'   =>  $linkman,
                    'link_mobile'   =>  $link_mobile,
                    'baby_name'   =>  $baby_name,
                    'baby_sex'   =>  $baby_sex,
                    'baby_birthday'   =>  $baby_birthday,
                );
                //存入SESSION
                $this->load->library('session');
                $this->session->set_userdata('book_member',$book_member);
                redirect("/purchasecourse/createbook?cp_id={$course_package_info['id']}&order_id={$course_package_info['order_id']}");
            }
            
            //获取用户信息
            $this->load->model('Member_model');
            $member_info = $this->Member_model->find(array('id'=>$this->member_id));
            
            $this->ct_template->write('_title', '约课');
            $this->ct_template->write_view('content', 'purchasecourse/index',array(
                'member_info'   =>  $member_info,
                'course_package_info'  =>  $course_package_info,
            ), FALSE);
            $this->ct_template->render();
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    
    /**
     * 第二步生成约课记录
     */
    public function createbook(){
        try {
            $cp_id = intval($this->input->get('cp_id'));    //获取课包ID
            if(empty($cp_id))throw new Exception('课包ID为空');
            
            $order_id = intval($this->input->get('order_id'));    //订单ID
            if(empty($order_id))throw new Exception('订单ID为空');
            
            $course_package_info = $this->IsHours($order_id);  //验证课包课时，并返回课包信息数据

            //获取教师列表
            $this->load->model('Teacher_model');
            $where = array(
                'nursery_id'=> $course_package_info['nursery_id'],
                'status'    =>1,
            );
            $teacher_list = $this->Teacher_model->findAll($where,'id,name,avatar,book_num,explain');
            if(empty($teacher_list))throw new Exception('教师列表为空');
            
            $this->ct_template->write('_title', '约课');
            $this->ct_template->write_view('content', 'purchasecourse/createbook',array(
                'nursery_id'   =>  $course_package_info['nursery_id'],
                'teacher_list' =>  $teacher_list,
                'course_package_info'  =>  $course_package_info,
                //'order_info'   =>  $order_info,
            ), FALSE);
            $this->ct_template->render();
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    /**
     * 入库
     */
    public function insertbook(){
        try {
            $this->load->library('session');
            $time_list = $this->session->time_list;
            if(empty($time_list))throw new Exception('时间列表获取失败');
            
            $teacher_id = intval($this->input->post('hi_teacher_id'));   //教师ID
            if(empty($teacher_id))throw new Exception('教师ID为空');
            
            $order_id = intval($this->input->post('order_id'));   //教师ID
            if(empty($order_id))throw new Exception('订单ID为空');
            
            $course_package_id = intval($this->input->post('course_package_id'));   //课包ID
            if(empty($course_package_id))throw new Exception('课包ID为空');
            $message = $this->input->post('message');   //留言
            
            $course_package_info = $this->IsHours($order_id);  //验证课包课时，并返回课包信息数据
            
            $book_member_id = $this->createBookMember();        //插入信息
            if(empty($book_member_id))throw new Exception();
            
            //入库
            $this->load->model('Book_model');
            foreach ($time_list as $val){
                $this->Book_model->insert(array(
                    'book_member_id'     =>  $book_member_id,
                    'member_id'     =>  $this->member_id,
                    'nursery_id'     =>  $course_package_info['nursery_id'],
                    'teacher_id'    =>  $teacher_id,
                    'order_id'      =>  $order_id,
                    'course_package_id'=>   $course_package_id,
                    'hours'         =>  1,
                    'book_date'     =>  $val['book_date'],
                    'book_date_start'=> $val['book_date_start'],
                    'book_date_end' =>  $val['book_date_end'],
                    'message'       =>  $message,
                    'create_date'   =>  date('Y-m-d H:i:s'),
                ));
            }
            //课时递减
            $this->load->model('Order_model');
            $hours_num = count($time_list);
            $sql = "update `order` set `surplus_hours` = `surplus_hours` - '$hours_num' where id = '$order_id' ";
            $this->Order_model->query($sql);
            
            //预约列表增加预约总数
            $this->load->model('Course_list_model');
            $sql = "update `course_list` set `total_book` = `total_book` + '$hours_num' where id = '{$course_package_info['course_list_id']}' ";
            $this->Course_list_model->query($sql);
            
            //增加老师上课次数
            $this->load->model('Teacher_model');
            $sql = "update `teacher` set `book_num` = `book_num` + '$hours_num' where id = '{$teacher_id}' ";
            $this->Teacher_model->query($sql);
            
            $this->load->library('session');
            $this->session->unset_userdata('time_list');
            
            $this->ct_template->write('_title', '约课');
            $this->ct_template->write_view('content', 'purchasecourse/insertbook',array(
                'course_package_info'  =>  $course_package_info,
            ), FALSE);
            $this->ct_template->render();
            
        }catch (Exception $e){
            $this->ct_template->write('_title', '错误提示');
            $this->ct_template->write_view('content', 'errors/html/warn', array('msg'=>$e->getMessage() ), FALSE);
            $this->ct_template->render();
        }
        
    }
    
    /**
     * 判断该时间是否已经被预约
     */
    public function isteachertime(){
        try {
            $return = array('code'=>10,'mgs'=>'','list'=>'');
            $this->load->library('session');
            $time_list = $this->session->time_list;
            if(empty($time_list))throw new Exception('时间列表获取失败');
            $time_list_ = array();
            foreach ($time_list as $val){
                $time_list_[$val['book_date']][] = $val;
            }
            $time_list = $time_list_;
            $teacher_id = intval($this->input->get('hi_teacher_id'));   //教师ID
            if(empty($teacher_id))throw new Exception('教师ID为空');
            
            //获取该老师已预约的课程
            $this->load->model('Book_model');
            $where = "teacher_id = '$teacher_id' AND status IN (0,1)";
            $book_list = $this->Book_model->findAll($where,'id,book_date,book_date_start,book_date_end');
            
            //echo '<pre>';print_r($book_list);print_r($time_list);die();
            
            //过滤已经约课教师
            if(!empty($book_list)){
                foreach ($book_list as $val){
                    if(!empty($time_list[$val['book_date']])){
                        $work_time = $time_list[$val['book_date']];
                        foreach ($work_time as $key_work=>$val_work){
                            //结束课程的1小时，不可预约
                            if($val['book_date_start'] <= $val_work['book_date_start'] && date('H:i:s',strtotime($val['book_date_end'])+3600) >= $val_work['book_date_end']){
                                throw new Exception($val['book_date'].' '.$val_work['book_date_start'].'~'.$val_work['book_date_end'].'的时间已被预约，请重新选择');
                            }
                        }
                    }
                }
            }
        }catch (Exception $e){
            $return['code'] = 11;
            $return['msg'] = $e->getMessage();
        }
        echo json_encode($return);exit();
    }
    /**
     * 返回教师可用时间
     */
    public function teachertime(){
        try {
            $return = array('code'=>11,'mgs'=>'','list'=>'');
            $order_id = intval($this->input->get('order_id'));    //订单ID
            if(empty($order_id))throw new Exception('订单ID为空');
            
            $course_package_info = $this->IsHours($order_id); //验证课时
            
            //session 取出已经选择的课程
            $this->load->library('session');
            $time_list = $this->session->time_list;
            
            //echo '<pre>';print_r($time_list);die();
            
            if($course_package_info['hours'] <= count($time_list))
                throw new Exception('您的课时已用完');
            
            $this->load->helper("arraytool");   //加载工具
            $teacher_id = intval($this->input->get('teacher_id'));    //获取园所ID
            if(empty($teacher_id))throw new Exception('教师ID为空');
            
            //获取教师时间段
            $this->load->model('Teacher_Work_Time_model');
            $where = array(
                'teacher_id'=>$teacher_id,
                'status'    =>  1,
            );
            $work_time = $this->Teacher_Work_Time_model->findAll($where,'work_week,work_time_start,work_time_end');
            if(empty($work_time))throw new Exception('此教师未设置可用时间段');
            $work_time = restByKey($work_time,'work_week',true);
                        
            $data_list = $this->getDateList(30);     //获取30天之后的时间
            
            //合并
            foreach ($data_list as $key=>$val){
                if(!empty($work_time[$val['week']])){
                    $data_list[$key]['list'] = $work_time[$val['week']];
                }
            }
            
            //获取该老师已预约的课程
            $this->load->model('Book_model');
            $where = "teacher_id = '$teacher_id' AND status IN (0,1)";
            $book_list = $this->Book_model->findAll($where,'id,book_date,book_date_start,book_date_end');
            
            //取出已选择课程session加入过滤
            if(empty($book_list))$book_list = array();
            if(empty($time_list))$time_list = array();
            $book_list = array_merge($book_list,$time_list);
            
            //echo '<pre>';print_r($book_list);die();
            //过滤已经约课教师
            if(!empty($book_list)){
                foreach ($book_list as $val){
                    if(!empty($data_list[$val['book_date']]['list'])){
                        $work_time = $data_list[$val['book_date']]['list'];
                        foreach ($work_time as $key_work=>$val_work){
                            //结束课程的1小时，不可预约
                            if($val['book_date_start'] <= $val_work['work_time_start'] && date('H:i:s',strtotime($val['book_date_end'])+3600) >= $val_work['work_time_end']){
                                unset($data_list[$val['book_date']]['list'][$key_work]);
                            }
                        }
                    }
                }
            }
            
            //过滤不存在的时间
            foreach ($data_list as $key=>$val){
                if(empty($val['list']))unset($data_list[$key]);
            }
            $return['code'] = 10;
            $return['list'] = $this->load->view('purchasecourse/teacher_time_list',array(
                'data_list'    =>  $data_list,
            ),true);;
        }catch (Exception $e){
            $return['msg'] = $e->getMessage();
        }
        
        echo json_encode($return);exit();
    }
    /**
     * 获取时间列表
     */
    private function getDateList($num = 30){
        $data = array();
        $weekArr=array("周日","周一","周二","周三","周四","周五","周六");
        $date_d = date('d')+3;
        for ($i=0;$i<$num;$i++){
            $d = date('Y-m-d',mktime(0,0,0,date('m'),$date_d+$i,date('Y')));
            $w = date('w',strtotime($d));
            $data[$d] = array(
                'date'  =>  $d,
                'week'  =>  $w,
                'week_name' =>  $weekArr[$w],
            );
        }
        //排除节假日
        $this->load->model('holiday_time_model');
        $holiday_list = $this->holiday_time_model->findAll(array('status'=>1),'holiday');
        if(!empty($holiday_list)){
        	$tmp = array();
        	foreach ($holiday_list as $key=>$val){
        		 $tmp[] = $val['holiday'];
        	}
        	foreach ($data as $key=>$val){
        		if(in_array(mb_substr($key,5),$tmp))unset($data[$key]);
        	}
        }
        return $data;
    }
    /**
     * 创建约课记录对应用户
     */
    private function createBookMember(){
        try {
            $this->load->library('session');
            $book_member = $this->session->book_member;
            if(empty($book_member))throw new Exception('');
            //插入地址记录
            $this->load->model('Book_Member_model');
            $book_member['create_date'] = date('Y-m-d H:i:s');
            $book_member_id = $this->Book_Member_model->insert($book_member);
            if(empty($book_member_id))throw new Exception('生成记录失败');
            
            //修改用户原始信息
            $this->load->model('Member_model');
            $this->Member_model->update($book_member,array('id'=>$this->member_id));
            
            return $book_member_id;
        }catch (Exception $e){
            return false;
        }
    }
//     /**
//      * 判断是否购买过次课包,并返回课包ID
//      */
//     private function IsOrder($order_id){
//         try {
//             $this->load->model('Order_model');
//             $fild = 'id,member_id,pay_fee,status,pay_way,course_cate_id,course_list_id,course_package_id';
//             $where = array(
//                 'id' =>  $order_id,
//                 'member_id' =>  $this->member_id,
//                 'status in(1,5)'    =>  NULL,
//             );
//             $order_info = $this->Order_model->find($where,$fild);
//             if(empty($order_info))throw new Exception('您未购买过次课程,或未支付');
//             return $order_info;            
//         }catch (Exception $e){
//             throw new Exception($e->getMessage());
//         }
//     }
    /**
     * 验证课包课时，并返回课包信息数据
     */
    private function IsHours($order_id){
        try {
            //获取订单信息
            $this->load->model('Order_model');
            $fild = 'id as order_id,member_id,pay_fee,status,pay_way,course_cate_id,course_list_id,course_package_id,hours,nursery_id';
            $where = array(
                'id' =>  $order_id,
                'member_id' =>  $this->member_id,
                'status in(1,5)'    =>  NULL,
            );
            $order_info = $this->Order_model->find($where,$fild);
            if(empty($order_info))throw new Exception('您未购买过次课程,或未支付');
            
            $this->load->model('Course_Package_model');
            $fild = 'id,title,course_list_id';
            $course_package_info = $this->Course_Package_model->find(array('id'=>$order_info['course_package_id']),$fild);
            if(empty($course_package_info))throw new Exception('此课包不存在');
            
            //计算课时
            $this->load->model('Book_model');
            $where = array();
            $where['course_package_id'] = $order_info['course_package_id'];
            $where['member_id'] = $this->member_id;
            $where['order_id'] = $order_id;
            $book_num = $this->Book_model->findCount($where);
            if($book_num >= $order_info['hours'])throw new Exception('此课包课时已满，无法继续预约');
            $order_info['hours'] -= $book_num; //减去已经预约的课时
            return array_merge($order_info,$course_package_info);
        }catch (Exception $e){
            throw new Exception($e->getMessage());
        }
    }
    /**
     * 用户已经选择的时间，存入SESSION
     */
    public function settimesession(){
        try {
            $return = array('code'=>11,'mgs'=>'','list'=>'');
            $set_date = trim($this->input->get('set_date'));   //时间串
            //处理字符串
            $_date = mb_substr($set_date,0,10,'utf-8');
            $_time = mb_substr($set_date,-11,11,'utf-8');
            $_time = explode('~',$_time);
            if(count($_time) != 2)throw new Exception('日期格式错误');

            
            //生成数组入SESSION
            $time_data[md5($set_date)] = array(
                'book_date'     =>  $_date,
                'book_date_start'   =>  date('H:i:s',strtotime($_time[0])),
                'book_date_end'     =>  date('H:i:s',strtotime($_time[1])),
            );
            //book_date,book_date_start,book_date_end
            //存入SESSION
            $this->load->library('session');
            $time_list = $this->session->time_list;
            if(!empty($time_list)){
                $time_data = array_merge($time_list,$time_data);
            }
            
            $this->session->set_userdata('time_list',$time_data);
            
            $return['code'] = 10;
                        
        }catch (Exception $e){
            $return['msg'] = $e->getMessage();
        }
        echo json_encode($return);exit();
    }
    /**
     * 用户删除的时间，做相应的删除操作
     */
    public function deltimesession(){
        try {
            $return = array('code'=>11,'mgs'=>'','list'=>'');
            $set_date = trim($this->input->get('set_date'));   //时间串
            
            $this->load->library('session');
            $time_list = $this->session->time_list;
            if(!empty($time_list)){
                unset($time_list[md5($set_date)]);
            }
    
            $this->session->set_userdata('time_list',$time_list);
    
            $return['code'] = 10;
    
        }catch (Exception $e){
            $return['msg'] = $e->getMessage();
        }
        echo json_encode($return);exit();
    }
    /**
     * 切换老师，删除所有session数据
     */
    public function deltimesessionall(){
        try {
            $return = array('code'=>11,'mgs'=>'','list'=>'');
    
            $this->load->library('session');
            
            $this->session->unset_userdata('time_list');
    
            $return['code'] = 10;
    
        }catch (Exception $e){
            $return['msg'] = $e->getMessage();
        }
        echo json_encode($return);exit();
    }
}













